#include "datamonitoring.h"
#include "ui_datamonitoring.h"
#include <QDateTime>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QDebug>

DataMonitoring::DataMonitoring(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DataMonitoring),
    m_refreshTimer(new QTimer(this))
{
    ui->setupUi(this);

    // 初始化数据库管理器
    dbManager = DatabaseManager::instance();
//    if (!dbManager->instance()) {
//        QMessageBox::critical(this, "错误", "无法连接到数据库服务器！");
//        return;
//    }

    // 设置默认显示实时监控标签页
    ui->tabWidget->setCurrentIndex(0);

    // 初始化数据模型
    m_historyModel = new QStandardItemModel(this);
    ui->dataTableView->setModel(m_historyModel);

    // 初始化图表
    setupRealtimeChart();
    setupHistoryChart();

    // 初始化定时器
    m_realtimeTimer = new QTimer(this);
    m_realtimeTimer->setInterval(m_updateInterval);

    // 初始化时间选择器
    ui->startTimeEdit->setDateTime(QDateTime::currentDateTime().addDays(-1));
    ui->endTimeEdit->setDateTime(QDateTime::currentDateTime());

    // 连接信号槽
    connect(ui->pauseButton, &QPushButton::clicked, this, &DataMonitoring::togglePause);
    connect(m_realtimeTimer, &QTimer::timeout, this, &DataMonitoring::updateRealtimeData);
    connect(ui->queryButton, &QPushButton::clicked, this, &DataMonitoring::queryHistoryData);
    connect(ui->exportButton, &QPushButton::clicked, this, &DataMonitoring::exportData);
    connect(ui->deviceComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &DataMonitoring::onDeviceChanged);
    //connect(ui->intervalSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
    //        this, &DataMonitoring::onIntervalChanged);

    // 填充设备列表
    populateDeviceComboBox();

    // 开始实时更新
    m_realtimeTimer->start();
}

void DataMonitoring::populateDeviceComboBox()
{
    ui->deviceComboBox->clear();
    ui->deviceComboBox->addItem("选择设备", -1);

    QString sql = "SELECT DISTINCT device_id FROM data ORDER BY device_id";
    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        QMessageBox::critical(this, "错误", "获取设备列表失败: " + response.mid(6));
        return;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList cols = row.split(" | ", QString::SkipEmptyParts);
        if (cols.size() >= 1) {
            int deviceId = cols[0].toInt();
            ui->deviceComboBox->addItem(QString("设备 %1").arg(deviceId), deviceId);
        }
    }
}

void DataMonitoring::onDeviceChanged(int index)
{
    if (index < 0) return;

    int deviceId = ui->deviceComboBox->itemData(index).toInt();
    setCurrentDevice(deviceId);
}

void DataMonitoring::setCurrentDevice(int deviceId)
{
    m_currentDeviceId = deviceId;
    updateRealtimeData();
    queryHistoryData();
}

QVector<QPointF> DataMonitoring::fetchRealtimeData()
{
    QVector<QPointF> data;
    if (m_currentDeviceId == -1) return data;

    QString sql = QString("SELECT temperature, humidity FROM data "
                         "WHERE device_id = %1 "
                         "ORDER BY timestamp DESC LIMIT 50").arg(m_currentDeviceId);

    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        qDebug() << "获取实时数据失败:" << response;
        return data;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList cols = row.split(" | ", QString::SkipEmptyParts);
        if (cols.size() >= 2) {
            double temp = cols[0].toDouble();
            double humidity = cols[1].toDouble();
            data.append(QPointF(temp, humidity));
        }
    }

    return data;
}

void DataMonitoring::updateRealtimeData()
{
    if (m_currentDeviceId == -1) return;

    QString sql = QString("SELECT timestamp, temperature, humidity FROM data "
                         "WHERE device_id = %1 "
                         "ORDER BY timestamp DESC LIMIT 1").arg(m_currentDeviceId);

    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        qDebug() << "查询失败:" << response;
        return;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    if (rows.isEmpty()) {
        qDebug() << "无数据";
        return;
    }

    QStringList cols = rows.first().split(" | ", QString::SkipEmptyParts);
    if (cols.size() < 3) return;

    QDateTime timestamp = QDateTime::fromString(cols[0], Qt::ISODate);
    double tempValue = cols[1].toDouble();
    double humidityValue = cols[2].toDouble();

    // 检查数据时间戳
    if (timestamp.secsTo(QDateTime::currentDateTime()) > 300) {
        qDebug() << "设备可能已离线，最后数据时间：" << timestamp;
    }

    // 检查温度异常
    if (tempValue > 30.0) {
        QString alarmContent = QString("温度过高: %1°C").arg(tempValue);
        triggerAlarm(m_currentDeviceId, alarmContent);
    }

    // 检查湿度异常
    if (humidityValue > 80.0) {
        QString alarmContent = QString("湿度过高: %1%").arg(humidityValue);
        triggerAlarm(m_currentDeviceId, alarmContent);
    }

    // 更新UI
    ui->tempLCD->display(tempValue);
    ui->humidityBar->setValue(humidityValue);

    // 更新图表
    qint64 time = timestamp.toMSecsSinceEpoch();
    if (m_tempSeries->count() == 0 || time > m_tempSeries->at(0).x()) {
        m_tempSeries->append(time, tempValue);
        m_humiditySeries->append(time, humidityValue);
    }

    // 限制数据量
    if (m_tempSeries->count() > 100) {
        m_tempSeries->remove(0);
        m_humiditySeries->remove(0);
    }

    // 更新X轴范围
    QList<QAbstractAxis*> xAxes = m_realtimeChart->axes(Qt::Horizontal);
    if (!xAxes.isEmpty()) {
        QDateTimeAxis *axisX = qobject_cast<QDateTimeAxis*>(xAxes.first());
        if (axisX) {
            axisX->setRange(QDateTime::currentDateTime().addSecs(-300),
                          QDateTime::currentDateTime());
        }
    }
}



void DataMonitoring::triggerAlarm(int deviceId, const QString &content)
{
    // 检查是否已经存在相同的未处理告警
    QString escapedContent = content;  // 创建 content 的副本
    escapedContent.replace("'", "''"); // 对副本进行操作

    QString checkSql = QString(
        "SELECT COUNT(*) FROM alarm_records "
        "WHERE device_id = %1 AND content = '%2' AND status = '未'"
    ).arg(deviceId)
     .arg(escapedContent);  // 使用处理后的字符串

    QString checkResponse = dbManager->sendRequest(checkSql);

    if (checkResponse.startsWith("Error:")) {
        qDebug() << "检查告警记录失败:" << checkResponse;
        return;
    }

    int existingAlarms = checkResponse.toInt();
    if (existingAlarms > 0) {
        qDebug() << "已存在相同未处理告警，不再重复触发";
        return;
    }
    // 获取当前时间戳
    QString currentTime = QDateTime::currentDateTime().toString(Qt::ISODate);

    // 不存在相同告警，创建新告警记录
    QString sql = QString("INSERT INTO alarm_records (device_id,timestamp, content, status) "
                       "VALUES (%1, '%2','%3', '未处理')")
                       .arg(deviceId)
                       .arg(currentTime)
                       .arg(escapedContent);

    QString response = dbManager->sendRequest(sql);
    if (response.startsWith("Error:")) {
        qDebug() << "触发告警失败:" << response;
    } else {
        qDebug() << "新告警已记录:" << content;
        SystemSetting::log(QString("添加告警规则失败: %1").arg(response), "alarm", "ERROR");
    }
}

QVector<QPair<QDateTime, QPair<double, double>>> DataMonitoring::fetchHistoryData(const QDateTime& start, const QDateTime& end)
{
    QVector<QPair<QDateTime, QPair<double, double>>> data;
    if (m_currentDeviceId == -1) return data;

    QString sql = QString("SELECT timestamp, temperature, humidity FROM data "
                         "WHERE device_id = %1 AND timestamp BETWEEN '%2' AND '%3' "
                         "ORDER BY timestamp")
                         .arg(m_currentDeviceId)
                         .arg(start.toString(Qt::ISODate))
                         .arg(end.toString(Qt::ISODate));

    QString response = dbManager->sendRequest(sql);

    if (response.startsWith("Error:")) {
        qDebug() << "获取历史数据失败:" << response;
        return data;
    }

    QStringList rows = response.split("\n", QString::SkipEmptyParts);
    foreach (const QString &row, rows) {
        QStringList cols = row.split(" | ", QString::SkipEmptyParts);
        if (cols.size() >= 3) {
            QDateTime timestamp = QDateTime::fromString(cols[0], Qt::ISODate);
            double temp = cols[1].toDouble();
            double humidity = cols[2].toDouble();
            data.append(qMakePair(timestamp, qMakePair(temp, humidity)));
        }
    }

    return data;
}

void DataMonitoring::queryHistoryData()
{
    if (m_currentDeviceId == -1) return;

    m_historyModel->clear();
    m_historyModel->setHorizontalHeaderLabels({"时间", "温度(℃)", "湿度(%)", "状态"});

    QDateTime start = ui->startTimeEdit->dateTime();
    QDateTime end = ui->endTimeEdit->dateTime();

    auto historyData = fetchHistoryData(start, end);
    for (const auto& item : historyData) {
        double temp = item.second.first;
        double humidity = item.second.second;
        QString status = "正常";

        // 检查异常数据
        if (temp > 30.0 || humidity > 80.0) {
            status = "异常";
            triggerAlarm(m_currentDeviceId,
                       QString("历史数据异常: 温度=%1, 湿度=%2")
                       .arg(temp).arg(humidity));
        }

        // 添加数据到表格
        QList<QStandardItem*> rowItems;
        rowItems << new QStandardItem(item.first.toString("yyyy-MM-dd hh:mm:ss"))
                << new QStandardItem(QString::number(temp, 'f', 1))
                << new QStandardItem(QString::number(humidity, 'f', 1))
                << new QStandardItem(status);
        m_historyModel->appendRow(rowItems);
    }

    updateHistoryChart();
}

void DataMonitoring::setupRealtimeChart()
{
    m_realtimeChart = new QChart();
    m_tempSeries = new QLineSeries();
    m_humiditySeries = new QLineSeries();

    m_tempSeries->setName("温度(℃)");
    m_humiditySeries->setName("湿度(%)");

    m_realtimeChart->addSeries(m_tempSeries);
    m_realtimeChart->addSeries(m_humiditySeries);

    // 创建并设置坐标轴
    QValueAxis *axisX = new QValueAxis;
    QValueAxis *axisY = new QValueAxis;

    axisX->setTitleText("时间");
    axisY->setTitleText("数值");

    m_realtimeChart->addAxis(axisX, Qt::AlignBottom);
    m_realtimeChart->addAxis(axisY, Qt::AlignLeft);

    m_tempSeries->attachAxis(axisX);
    m_tempSeries->attachAxis(axisY);
    m_humiditySeries->attachAxis(axisX);
    m_humiditySeries->attachAxis(axisY);

    m_realtimeChart->setTitle("实时监控数据");

    QChartView *chartView = new QChartView(m_realtimeChart);
    chartView->setRenderHint(QPainter::Antialiasing);
    ui->chartLayout->addWidget(chartView);
}

void DataMonitoring::setupHistoryChart()
{
    m_historyChart = new QChart();
    m_historyChart->setTitle("历史数据趋势");

    QChartView *historyChartView = new QChartView(m_historyChart);
    historyChartView->setRenderHint(QPainter::Antialiasing);
    ui->historyChartLayout->addWidget(historyChartView);
}


void DataMonitoring::togglePause()
{
    m_isPaused = !m_isPaused;
    if(m_isPaused) {
        m_realtimeTimer->stop();
        ui->pauseButton->setText("继续");
    } else {
        m_realtimeTimer->start();
        ui->pauseButton->setText("暂停");
    }
}

void DataMonitoring::updateHistoryChart()
{
    m_historyChart->removeAllSeries();

    QLineSeries *tempSeries = new QLineSeries();
    QLineSeries *humiditySeries = new QLineSeries();

    tempSeries->setName("温度");
    humiditySeries->setName("湿度");

    for(int row = 0; row < m_historyModel->rowCount(); ++row) {
        qreal temp = m_historyModel->item(row, 1)->text().toDouble();
        qreal humidity = m_historyModel->item(row, 2)->text().toDouble();
        tempSeries->append(row, temp);
        humiditySeries->append(row, humidity);
    }

    m_historyChart->addSeries(tempSeries);
    m_historyChart->addSeries(humiditySeries);
    m_historyChart->createDefaultAxes();
}

void DataMonitoring::exportData()
{
    QString fileName = QFileDialog::getSaveFileName(this, "导出数据", "", "CSV文件 (*.csv)");
    if(fileName.isEmpty()) return;

    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);

        // 写入表头
        for(int col = 0; col < m_historyModel->columnCount(); ++col) {
            out << m_historyModel->horizontalHeaderItem(col)->text();
            if(col < m_historyModel->columnCount() - 1) out << ",";
        }
        out << "\n";

        // 写入数据
        for(int row = 0; row < m_historyModel->rowCount(); ++row) {
            for(int col = 0; col < m_historyModel->columnCount(); ++col) {
                out << m_historyModel->item(row, col)->text();
                if(col < m_historyModel->columnCount() - 1) out << ",";
            }
            out << "\n";
        }
    }
}


void DataMonitoring::startDataRefresh()
{
    if(!m_refreshTimer->isActive()) {
        m_refreshTimer->start();
        qDebug() << "Data refresh started";
    }
}

void DataMonitoring::stopDataRefresh()
{
    if(m_refreshTimer->isActive()) {
        m_refreshTimer->stop();
        qDebug() << "Data refresh stopped";
    }
}

void DataMonitoring::onIntervalChanged(int value)
{
    m_updateInterval = value;
    m_realtimeTimer->setInterval(m_updateInterval);
}

DataMonitoring::~DataMonitoring()
{
    delete ui;
    delete m_realtimeChart;
    delete m_historyChart;
}
